#include "editor_process.h"

#include <glib.h>

GPid starteditor(editor_process *ep);
static void editor_process_closed(GPid, gint status, gpointer data);

editor_process::editor_process(std::string url) throw(editor_process_exception)
    : _url(url)
{
    Gtk::Socket* socket = Gtk::manage(new Gtk::Socket());
    this->add(*socket);
    _id = socket->get_id();
    _pid = starteditor(this);
    if (_pid == -1) throw editor_process_exception("Could not start gvim");
    g_child_watch_add(_pid, (GChildWatchFunc)editor_process_closed, this);
    set_size_request(720, 600);
    show_all();
}

editor_process::~editor_process()
{
    close();
}

void editor_process::close()
{
    g_spawn_close_pid(_pid);
    // TODO:close the window
}

void editor_process::raise()
{

}

static void editor_process_closed(GPid, gint status, gpointer data)
{
    // TODO: Need to inform the main loop that this process is closed
    // so the window is removed from the open windows list.
    editor_process *ep = (editor_process*)data;
    ep->close();
}

GPid starteditor(editor_process* ep)
{
    gint argcp, outfd, errfd;
    gchar **argvp;
    GError *err;
    GPid pid;

    char *cmd = g_strdup_printf("gvim --socketid %d %s", ep->id(), (ep->url()).c_str());
    g_shell_parse_argv(cmd, &argcp, &argvp, &err);
    if (!g_spawn_async_with_pipes(".", argvp, NULL, 
                (GSpawnFlags)(G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_SEARCH_PATH),
                NULL, NULL, &pid, NULL, &outfd, &errfd, &err)) {
        g_error("Could not start gvim");
        return(-1);
    }
    return(pid);
}

